﻿

function loadJSX(fileName)
{
        var cs = new CSInterface();
        var extensionRoot = cs.getSystemPath(SystemPath.EXTENSION) + "/js/";
        cs.evalScript('$.evalFile("' + extensionRoot + fileName + '")');
}
var cropBox = new Array;
//loadJSX("json2.js")
//mMap = JSON.parse(map_data)
//console.log(mMap)
function printData(data){
    var fs = require('fs'); // 引入fs模块
    // 打开文件
    /*
    fs.open("C:/Program Files/Adobe/Adobe Illustrator CC 2017/CEP/extensions/com.acc.ext'/data.json", 'w', function(err, fd) {
        if (err) {
            throw err;
        }
        console.log('成功打开文件.');
        var buffer = new Buffer(data);
        // 读取文件
        fs.writeFile(fd, data,function(err, bytesWritten, buffer) {
            if (err) {
                throw err;
            }
    
            console.log('写入成功.');
            // 打印出buffer中存入的数据
            console.log(bytesWritten, buffer.slice(0, bytesWritten).toString());
    
            // 关闭文件
            fs.close(fd);
        });
    });*/
    fs.writeFile("C:/Program Files/Adobe/Adobe Illustrator CC 2017/CEP/extensions/com.acc.ext'/data.json"
    , data, function(err) {
        if(err) {
            return console.log(err);
        }
        console.log("File saved successfully!");
    });
}
function test_dodo(){
    //var message = "000";
    //var message1 ="111";
    //alert("dodo('"+message +"'"+","+"'"+message1 +"');");
    var person='{"name":"shily","sex":"女","age":"23"}'
    var cs = new CSInterface();
    cs.evalScript("dodo('"+ person + "');");
}

function transCor(pt){
    //alert(mMap.bounds[3])
    var w = mMap.bounds[2]- mMap.bounds[0];
    var h = mMap.bounds[1] - mMap.bounds[3];
    var xscale = (cropBox[2] - cropBox[0])/w;
    var yscale = (cropBox[1] - cropBox[3])/h;
    if(xscale>yscale)
    {
      pt.screen_y = yscale*(parseFloat(pt.y)-mMap.bounds[1]);
      pt.screen_x = yscale*(parseFloat(pt.x)-mMap.bounds[0]);
    }
    else 
    {
      pt.screen_y = xscale*(parseFloat(pt.y)-mMap.bounds[1]);
      pt.screen_x = xscale*(parseFloat(pt.x)-mMap.bounds[0]);
    }
    //alert(JSON.stringify(pt))
}
function transCors(pts){
   for(var i = 0; i < pts.length ;i++)
        transCor(pt[i])
}

var loadTemplate = function()
{
    //var selid = document.getElementById("layer");
   
    var fs = require("fs");
    var result = window.cep.fs.showOpenDialogEx (false, false, "标题", "D:/", ["json"] , "文件类型说明");
    alert(result.data.toString().substring(result.data.toString().lastIndexOf('/')+1))
    fs.readFile(result.data.toString(), "utf-8", function(error, data) {
        if (error) return console.log("读取文件失败,原因是" + error.message);
        var json_obj = JSON.parse(data);
        alert(json_obj.name)
        
    });
}
var drawFeatures = function(){

}
var setPointStyle = function(i){

}

var setMapStyle= function(){

}

var draw  = function(){
    console.log(mMap.geoLayers)
    var cs = new CSInterface();
    for(var i = 0; i< mMap.geoLayers.length;i++){
        //addLayer
        //var lyr_name = mMap.geoLayers[i].layer_name;
        //cs.evalScript("addLayer('"+lyr_name +"');");
        var features = mMap.geoLayers[i].features;
        for(var j = 0; j< features.length;j++){
            var feature =  JSON.parse(JSON.stringify(features[j]));
            //var feature_str = JSON.stringify(feature);
            if(feature.feature_type == "esriGeometryPoint")
            {
                //var pts = feature.geometry;
                //console.log(pts)
                //var person={"name":"shily","sex":"女","age":"23"}
                //var feature_str = JSON.stringify(feature)
                //console.log(feature_str)
                //alert(feature_str)
                //cs.evalScript("drawPoint('"+feature_str +"');");
            }
            if(feature.feature_type == "esriGeometryPolygon")
            {
                //var pts = feature.geometry;
                //console.log(pts)
                //var person={"name":"shily","sex":"女","age":"23"}
                //var feature_str = JSON.stringify(feature)
                //console.log(feature_str)
                //alert(feature_str)
                //cs.evalScript("drawPoly('"+feature_str +"');");
            }
            //var pts_draw = pts.map(obj => {return [obj.screen_x,obj.screen_y]})
            //console.log(pts_draw)
            //for(var k = 0; k< features.length;j++){
            //var cs = new CSInterface();
        }
    }
}
var phareFeatures =function(jsono){
    var geo_features = new Array();
    var pt_bounds = new Array();
    pt_bounds = jsono.Bounds;
    //if(pt_bounds === undefined)
        //alert("输入的json数据不含四至信息，请检查输入数据！");
    //else{
            if(jsono.geometryType === "esriGeometryPolygon")
            {
                for(var i = 0; i<jsono.features.length;i++)
                {
                    var geo_feature = new geoFeature();
                    
                    //var properties = JSON.parse(JSON.stringify(jsono.features[i].attributes));
                    //geo_feature.feature_properties = properties;
                    geo_feature.feature_type = jsono.geometryType;
                    //geo_feature.geometry = jsono.features[i].geometry;
                    var rings = new Array();
                    rings = jsono.features[i].geometry.rings;
                    for(var j = 0; j<rings.length;j++)
                    {
                        var pts = new Array();
                        pts = rings[j];
                        for(var k = 0; k<pts.length;k++)
                        {
                            var geo_pt = new geoPt;
                            //alert(JSON.stringify(pts[k]))
                            //alert(typeof(pts[k]));
                            //alert(pts[k][0]);
                            geo_pt.x = pts[k][0];
                            geo_pt.y = pts[k][1];
                            transCor(geo_pt)
                            geo_feature.geometry.push(geo_pt)
                            //alert(JSON.stringify(geo_pt))
                        }
                    }

                    var feature_style = new polyStyle();
                    geo_feature.feature_style = feature_style;
                    //alert(JSON.stringify(geo_feature))
                    geo_features.push(geo_feature);
                }
            }
            if(jsono.geometryType === "esriGeometryPoint")
            {
                for(var i = 0; i<jsono.features.length;i++)
                {
                    var geo_feature = new geoFeature();
                    //var rings = new Array();
                    //rings = jsono.features[i].geometry.rings;
                    //var properties =  JSON.parse(JSON.stringify(jsono.features[i].attributes));
                    //geo_feature.feature_properties = properties;
                    geo_feature.feature_type = jsono.geometryType;
                    //geo_feature.geometry = jsono.features[i].geometry;
                    var geo_pt = new geoPt;
                    geo_pt.x = jsono.features[i].geometry.x;
                    geo_pt.y = jsono.features[i].geometry.y;
                    transCor(geo_pt)
                    geo_feature.geometry.push(geo_pt)
                    //alert(JSON.stringify(geo_pt))
                    var  feature_style = new pointStyle();
                    geo_feature.feature_style = feature_style;
                    //alert(JSON.stringify(geo_feature))
                    geo_features.push(geo_feature);
                }


                /*
                var pos = 0;
                var pts = new Array();
                for(var i = 0; i<jsono.features.length;i++)
                {
                    pts[pos] = jsono.features[i].geometry.x;
                    pts[pos+1] = jsono.features[i].geometry.y;
                    pos = pos + 2;
                }*/
                //alert(pts.length);
                //var pts = new Array();
                //var pt = Object.create({})
                //"x" : 535262.38985479739,"y" : 2518179.2034175266
                //pt.x = 535262;
                //pt.y =  2518179;

                //pt.name = "test"
                //pts.push(pt);
                //var pts_tmp = JSON.stringify(pts)
                //alert(pts_tmp)
                //var cs = new CSInterface();
                //var test = ""
                //cs.evalScript("getCanvasSize();",function(result){
                    //alert(result)
                //});
                
                //var layer_name = result.data.toString().substring(result.data.toString().lastIndexOf('/')+1,result.data.toString().lastIndexOf('.'));
                //cs.evalScript("AddPoints('"+pts_tmp +"'"+","+ "'"+ layer_name + "'" + ","+"'"+pt_bounds +"');");
                //selid.options.add(new Option(layer_name,layer_name));
            }
        //}
    //alert(JSON.stringify(geo_features))
    return geo_features
}

var getFileContent = function(path,layer){
    var fs = require("fs");
    /* 异步读取
    fs.readFile(path, "utf-8", function(error, data){
        if (error){
            alert("读取文件失败,原因是" + error.message);
            return ;
        }
        alert("成功读取" + path);
        var jsono = JSON.parse(data);
        var tmp = phareFeatures(jsono)
        alert("该图层有" + tmp.length + "个要素")
        layer.features = tmp;
        alert("组装好的图层有" + layer.features.length + "个要素")
        //console.log("读取文件成功,内容是" + data);
    });*/
    // 同步读取
    var data = fs.readFileSync(path, "utf-8");
    alert("成功读取" + path);
    var jsono = JSON.parse(data);
    var tmp = phareFeatures(jsono)
    //alert("该图层有" + tmp.length + "个要素")
    layer.features = tmp;
    //alert("组装好的图层有" + layer.features.length + "个要素")

}
var parseTemplate = function(data_obj){
    //test_dodo()
    var data_pathes = data_obj.data;
    mMap.name = data_obj.name;
    mMap.bounds = JSON.parse(JSON.stringify(data_obj.Bounds));
    //alert(mMap.bounds[3])
    for(var i = 0; i<data_pathes.length;i++){
        var layer_name = data_pathes[i].toString().substring(data_pathes[i].toString().lastIndexOf('/')+1,data_pathes[i].toString().lastIndexOf('.'));
        //alert(layer_name)
        var layer = new geoLayer()
        layer.source = data_pathes[i].toString();
        layer.layer_name = layer_name; 
        for(var j=0; j< data_obj.style.length;j++){
            if(data_obj.style[j].name == layer_name)
            {
                layer.method = data_obj.style[j].methods;
                layer.style_index = data_obj.style[j].style_index;
                layer.field =  data_obj.style[j].class_field;
                break;
            }
        }
        getFileContent(data_pathes[i].toString(),layer);
        mMap.geoLayers.push(layer)
    }
    console.log("所有图层读取完毕，共" + mMap.geoLayers.length + "个图层")
    //alert("所有图层读取完毕，共" + mMap.geoLayers.length + "个图层")
    draw();
    //alert(mMap.name)
    //printData(JSON.stringify(mMap))
    //for(var j = 0; j< mMap.geoLayers.length;j++){
        //alert("图层" +  mMap.geoLayers[j].layer_name + "有" +mMap.geoLayers[j].features.length + "个要素")
    //}
    
}

var openFileDialog = function()
{ 
    
    var cs = new CSInterface();
    cs.evalScript("getCanvasSize();",function(result){
        cropBox = result.split(',');
        //alert(cropBox[0]);
        var fs = require("fs");
        var result = window.cep.fs.showOpenDialogEx (false, false, "标题", "D:/", ["json"] , "文件类型说明");
        //alert(result.data.toString())
        fs.readFile(result.data.toString(), "utf-8", function(error, data) {
            if (error) return console.log("读取文件失败,原因是" + error.message);
            var json_obj = JSON.parse(data);
            alert("成功读取配置文件");
            //alert(json_obj.name)
            parseTemplate(json_obj);
            
        });
    }); 
    //test_dodo();
}
